package com.suapi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suapi.project.common.*;
import com.suapi.project.model.dto.interfaceInfo.InterfaceInfoAddRequest;
import com.suapi.project.model.dto.interfaceInfo.InterfaceInfoInvokeRequest;
import com.suapi.project.model.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.suapi.project.model.dto.interfaceInfo.InterfaceInfoUpdateRequest;
import com.suapi.project.model.enums.InterfaceInfoStatusEnum;
import com.suapi.project.model.enums.UserInterfaceInfoStatusEnum;
import com.suapi.project.service.UserInterfaceInfoService;
import com.suapi.project.service.UserService;
import com.suapi.suapiclientsdk.client.SuapiClient;
import com.suapi.project.annotation.AuthCheck;
import com.suapi.project.constant.CommonConstant;
import com.suapi.project.exception.BusinessException;
import com.suapi.project.service.InterfaceInfoService;
import com.suapi.suapicommon.model.entity.InterfaceInfo;
import com.suapi.suapicommon.model.entity.User;
import com.suapi.suapicommon.model.entity.UserInterfaceInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 接口管理
 *
 * @author suapi
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    @Resource
    private SuapiClient suapiClient;

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        log.info("add--controller{}",String.valueOf(interfaceInfoAddRequest));
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        //获取用户，同时可以判断是否登录
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/update")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                            HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取（登录才可以访问）
     *
     * @param id
     * @return
     */
    @AuthCheck(anyRole = {"admin","user"})
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表（登录才可以访问）
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @AuthCheck(anyRole = {"admin","user"})
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String description = interfaceInfoQuery.getDescription();
        // content 需支持模糊搜索
        //interfaceInfoQuery.setContent(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }


    /**
     * 上线接口
     * @param idRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/online")
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {
        //首先判断传入的参数是否为空
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("上线接口功能，idRequest：{}",idRequest);
        // 判断接口是否存在
        Long id = idRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 判断接口是否可以调用
        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        //需要自己重新new一个SuapiClient类
        SuapiClient suClient = new SuapiClient(accessKey,secretKey);
        Class<? extends SuapiClient> suClientClass = suClient.getClass();
        // 根据接口名称获取方法名
        Method method;
        Object invoke = null;
        try {
            //根据是否传入参数，来判断方法是有参的还是无参的
            if (!StringUtils.isAnyBlank(oldInterfaceInfo.getRequestParams())){
                // 由于我们在前端使用了json编辑器，导致我们的参数是json字符串，所以需要去掉其中的空格和换行符
                String requestParams = oldInterfaceInfo.getRequestParams().replaceAll("\\s+", "");
                method = suClientClass.getMethod(oldInterfaceInfo.getName(), String.class);
                invoke = method.invoke(suClient, requestParams);
            }else{
                method = suClientClass.getMethod(oldInterfaceInfo.getName());
                invoke = method.invoke(suClient);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"接口调用失败");
        }
        // 修改接口状态为上线状态
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        interfaceInfo.setId(id);
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 下线接口
     * @param idRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/offline")
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {
        //首先判断传入的参数是否为空
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("下线接口功能，idRequest：{}",idRequest);
        // 判断接口是否存在
        Long id = idRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 修改接口状态为下线状态
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        interfaceInfo.setId(id);
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }


    /**
     * 调用接口
     * @param interfaceInfoInvokeRequest
     * @param request
     * @return
     */
    @AuthCheck(anyRole = {"admin","user"})
    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest,
                                                      HttpServletRequest request) {
        //首先判断传入的参数是否为空
        if (interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        log.info("调用接口功能，InterfaceInfoInvokeRequest：{}",interfaceInfoInvokeRequest);
        // 判断接口是否存在
        Long id = interfaceInfoInvokeRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //判断接口的状态是否为上线状态
        if (oldInterfaceInfo.getStatus() == InterfaceInfoStatusEnum.OFFLINE.getValue()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口未上线");
        }
        //获取当前用户的accessKey和secretKey
        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        if (StringUtils.isAnyBlank(accessKey,secretKey)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"调用失败，请开通API权限");
        }
        // 检查用户是否被禁用
        int userInterfaceInfoStatus = userInterfaceInfoService.getUserInterfaceInfoStatus(id, loginUser.getId());
        if (userInterfaceInfoStatus == UserInterfaceInfoStatusEnum.off.getValue()){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"调用失败，用户被禁用本接口");
        }
        //判断用户是否有调用次数
        int haveTimes = userInterfaceInfoService.isHaveTimes(id, loginUser.getId());
        if (haveTimes == -1){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"调用失败，接口未开通");
        }
        if (haveTimes == 0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"调用失败，接口调用次数不足");
        }
        //需要自己重新new一个SuapiClient类
        SuapiClient suClient = new SuapiClient(accessKey,secretKey);
        Class<? extends SuapiClient> suClientClass = suClient.getClass();
        // 根据接口名称获取方法名
        Method method;
        String result = null;
        try {
            //根据是否传入参数，来判断方法是有参的还是无参的
            if (!StringUtils.isAnyBlank(interfaceInfoInvokeRequest.getUserRequestParams())){
                method = suClientClass.getMethod(oldInterfaceInfo.getName(), String.class);//参数类型直接用String.class，转为对应的类型由SDK进行解析
                return ResultUtils.success(method.invoke(suClient,interfaceInfoInvokeRequest.getUserRequestParams()));
            }
            method = suClientClass.getMethod(oldInterfaceInfo.getName());
            return ResultUtils.success(method.invoke(suClient));
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"接口调用失败");
        }
    }

    /**
     * 开通接口权限
     * @param interfaceInfoId
     * @param request
     * @return
     */
    @AuthCheck(anyRole = {"admin","user"})
    @PostMapping("/open")
    public BaseResponse<Boolean> openPermission(@RequestParam("id") Long interfaceInfoId, HttpServletRequest request){
        if (interfaceInfoId == null || request == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        //判断是否已经开通了API权限
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        if (StringUtils.isAnyBlank(accessKey,secretKey)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"请先开通API权限");
        }
        Long userId = loginUser.getId();
        return ResultUtils.success(interfaceInfoService.openPermission(interfaceInfoId,userId));
    }


}